package com.jy.modules.cims.component.loan;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmCooperorgDealService;
import com.jy.modules.cims.component.common.service.TCMmCreditDealDetailService;
import com.jy.modules.cims.component.deal.ICDeal;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDealDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmQuotaLoanDetailDTO;
import com.jy.modules.cims.data.dao.BuyBackDao;
import com.jy.modules.cims.data.dao.DealDao;
import com.jy.modules.cims.data.dao.ImgurlDao;
import com.jy.modules.cims.data.dao.LoanDao;
import com.jy.modules.cims.data.dao.QuotaLoanDetailDao;
import com.jy.modules.cims.data.dto.DealDetailDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.ImgurlDto;
import com.jy.modules.cims.data.dto.LoanDto;
import com.jy.modules.cims.data.dto.PlcImagesDto;
import com.jy.modules.cims.data.dto.QuotaLoanDetailDto;
import com.jy.modules.cims.data.dto.QuotaLoanDto;
import com.jy.modules.cims.data.dto.RepayPlanDto;
import com.jy.modules.cims.data.dto.loan.LoanBorrowerAssetDto;
import com.jy.modules.cims.data.dto.loan.LoanBorrowerCreditInfoDto;
import com.jy.modules.cims.data.dto.loan.LoanBorrowerDto;
import com.jy.modules.cims.data.dto.loan.LoanBorrowerEntityDto;
import com.jy.modules.cims.data.dto.loan.LoanBorrowerJobDto;
import com.jy.modules.cims.data.dto.loan.LoanBorrowerLoanInfoDto;
import com.jy.modules.cims.data.dto.loan.LoanDealBaseInfoDto;
import com.jy.modules.cims.data.interact.api.request.RequestLoanRedemptionApplyLoanDTO;

/**
 * 
 */
@Service("com.jy.modules.cims.component.loan.CLoanImpl")
public class CLoanImpl implements ICLoan {
	@Autowired
	private LoanDao loanDao;

	@Autowired
	public ImgurlDao imgurlDao;

	@Autowired
	public DealDao dealDao;

	@Autowired
	public QuotaLoanDetailDao quotaLoanDetailDao;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCooperorgDealService")
	protected TCMmCooperorgDealService cooperorgDealService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.deal.CDealImpl")
	public ICDeal iCDeal;
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDealDetailService")
	protected TCMmCreditDealDetailService creditDealDetailService;
	
	@Autowired
	protected BuyBackDao buyBackDao;
	
	/**
     * 
     */
	public CLoanImpl() {

	}

	/**
	 * @param detail
	 * @return
	 */
	public LoanDto dealDetailToLoan(DealDetailDto detail) {
		return null;
	}

	/**
	 * @param dto
	 * @return
	 */
	public DealDetailDto loanToDealDetail(LoanDto dto) {
		return null;
	}

	/**
	 * 保存贷款信息
	 * 
	 * @param dto
	 * @return
	 */
	public void saveInfo(LoanDto dto) {

	}

	/**
	 * 获得贷款还款计划
	 * 
	 * @param loanTransId
	 * @return
	 */
	public List<RepayPlanDto> getRepayPlan(String loanTransId) {
		return null;
	}
	
	/**
	 * 债权赎回流水号
	 * 
	 * @param quotaCode
	 * @return
	 */
	public String doGetDealCode() throws Exception {
		return iCDeal.createDealCode(CimsConstant.BIZNO_TYPE_REDEMPTION);
	}

	/**
	 * @author lizhiqiang
	 * @date 2015-1-23 下午5:16:56
	 * @see com.jy.modules.cims.component.creditRight.ICCreditRight#updateTCMmQuotaCreditDetailStatusByIntoAppCodes(com.jy.modules.cims.data.dto.QuotaLoanDto)
	 */
	@Override
	public void updateTCMmQuotaLoanDetailStatusByContractNos(QuotaLoanDto qldto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", qldto);
		paramMap.put("intoAppCodes", qldto.getIntoAppCodes());
		loanDao.updateTCMmQuotaLoanDetailStatusByContractNos(paramMap);
	}

	/**
	 * @description 根据交易流水号查询贷款明细关联的影像URL登记信息
	 * @param dealCode
	 * @return
	 */
	public List<ImgurlDto> searchUploadImgurlByDealCode(String dealCode) {
		if (null == dealCode) {
			return null;
		}

		ImgurlDto searchImgurl = new ImgurlDto();
		searchImgurl.setDealCode(dealCode);

		return imgurlDao.searchUploadImgurl(SearchParamUtil.getSearchParam(searchImgurl));
	}

	public List<ImgurlDto> searchUploadImgurls(String contractNo,String attachNames) throws Exception{
		ImgurlDto searchImgurl = new ImgurlDto();
		searchImgurl.setAttachNames(attachNames);
		searchImgurl.setContractNo(contractNo);
		return imgurlDao.searchImgurlByAttachNames(SearchParamUtil.getSearchParam(searchImgurl));
	}
	
	/**
	 * @description 根据交易流水号查询贷款明细关联的影像URL登记信息
	 * @param dealCode
	 * @return
	 */
	public List<ImgurlDto> searchImgurlBydealCode(String dealCode) {
		if (null == dealCode) {
			return null;
		}

		ImgurlDto searchImgurl = new ImgurlDto();
		searchImgurl.setDealCode(dealCode);

		return imgurlDao.searchImgurlBydealCode(SearchParamUtil.getSearchParam(searchImgurl));
	}

	/**
	 * @description 根据主键更新上传文件状态
	 * @param id
	 * @param fileUploadStatus
	 */
	public void updateImgurlFileUploadStatusById(long id, String fileUploadStatus) throws Exception {
		ImgurlDto imgurl = new ImgurlDto();

		imgurl.setId(id);
		imgurl.setFileUploadStatus(fileUploadStatus);

		imgurlDao.updateImgurlFileUploadStatus(SearchParamUtil.getSearchParam(imgurl));
	}

	/**
	 * @description 根据贷款交互状态获取申请流水号
	 * @param loanEachStatus
	 * @return
	 */
	public List<DealDto> getDealCodeByLoanEachStatus(String loanEachStatus) throws Exception {
		if (null == loanEachStatus) {
			return null;
		}

		DealDto dto = new DealDto();
		dto.setLoanEachStatus(loanEachStatus);

		return dealDao.getDealCodeByLoanEachStatus(SearchParamUtil.getSearchParam(dto));
	}

	/**
	 * @description 根据交易流水号修改贷款交互状态
	 * @param dealCode
	 * @throws Exception
	 */
	public void updateLoanEachStatusByDealCode(String dealCode, String loanEachStatus) throws Exception {
		if (null == dealCode || null == loanEachStatus) {
			return;
		}

		DealDto dto = new DealDto();
		dto.setDealCode(dealCode);
		dto.setLoanEachStatus(loanEachStatus);

		dealDao.updateLoanEachStatusByDealCode(SearchParamUtil.getSearchParam(dto));
	}

	/**
	 * @description 根据合同号批量更新贷款明细表的贷款交互状态 loan_each_status
	 * @param loanEachStatus
	 *            贷款交互状态
	 * @param dealCode
	 *            流水号
	 * @param contractNos
	 *            多个合同号,中间以逗号分隔开.
	 * @throws Exception
	 */
	public void updateDetailLoanEachStatusByContractNos(String loanEachStatus, String dealCode, String contractNos) throws Exception {
		if (null == dealCode || null == loanEachStatus || null == contractNos) {
			return;
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("loanEachStatus", loanEachStatus);
		paramMap.put("dealCode", dealCode);
		paramMap.put("contractNos", contractNos);
		loanDao.updateTCMmQuotaLoanDetailForLoanEachStatusByContractNos(paramMap);
	}

	/**
	 * @description 根据申请流水号查询获取记录条数
	 * @param quotaCode
	 * @return
	 */
	public int getQuotaLoanDetailCountByQuotaCode(String quotaCode) {
		if (!SimpleStringUtils.hasText(quotaCode)) {
			return 0;
		}

		QuotaLoanDetailDto dto = new QuotaLoanDetailDto();
		dto.setQuotaCode(quotaCode);

		return quotaLoanDetailDao.searchQuotaLoanDetailCountByQuotaCode(SearchParamUtil.getSearchParam(dto));
	}

	/**
	 * @description 根据额度申请编号和合同号查询额度申请贷款明细
	 * @param quotaCode
	 * @return
	 */
	public List<TCMmQuotaLoanDetailDTO> getQuotaLoanDetailByQuotaCodeAndContractNoList(String quotaCode, List<String> contractNoList) {
		if (!SimpleStringUtils.hasText(quotaCode) || CollectionsUtils.isEmpty(contractNoList)) {
			return null;
		}

		QuotaLoanDetailDto dto = new QuotaLoanDetailDto();
		dto.setQuotaCode(quotaCode);
		dto.setContractNoList(contractNoList);

		return quotaLoanDetailDao.getQuotaLoanDetailByQuotaCodeAndContractNoList(SearchParamUtil.getSearchParam(dto));
	}

	/**
	 * @description 根据额度申请查询获取额度明细
	 * @param dto
	 * @return
	 */
	public List<QuotaLoanDetailDto> getQuotaLoanDetailByQuotaLoanDetai(QuotaLoanDetailDto dto) {
		return quotaLoanDetailDao.searchQuotaLoanDetailByQuotaLoan(SearchParamUtil.getSearchParam(dto));
	}
	
	/**
	 * @Description 批量修改额度额度明细
	 * @author shengzhoutao
	 * @param paramMap
	 * @return
	 */
	public int updateQuotaLoanDetailDealStatus(Map<String, Object> paramMap){
		return quotaLoanDetailDao.updateQuotaLoanDetailDealStatus(paramMap);
	}

	public List<PlcImagesDto> findPlcImagesByCpcAndDealType(Map<String, Object> paramMap){
		return imgurlDao.findPlcImagesByCpcAndDealType(paramMap);
	}
	
	public List<PlcImagesDto> findPlcImagesByDealCodeContractNo(Map<String, Object> paramMap){
		return imgurlDao.findPlcImagesByDealCodeContractNo(paramMap);
	}

	public List<LoanDealBaseInfoDto> getLoanDealBaseInfoListByPaging(Map<String, Object> paramMap) {
		return loanDao.getLoanDealBaseInfoListByPaging(paramMap);
	}

	public LoanBorrowerDto getLoanBorrowerInfoByLoanNumber(String loanNumber) {
		Map<String, Object> paramMap = new HashMap<String, Object>(1);
		paramMap.put("loanNumber", loanNumber);
		List<LoanBorrowerDto> list = loanDao.getLoanBorrowerInfoByLoanNumber(paramMap);
		if (list == null || list.isEmpty())
			return null;
		return list.get(0);
	}

	public List<LoanBorrowerJobDto> getLoanBorrowerJobsByLoanNumber(String loanNumber) {
		Map<String, Object> paramMap = new HashMap<String, Object>(1);
		paramMap.put("loanNumber", loanNumber);
		List<LoanBorrowerJobDto> list = loanDao.getLoanBorrowerJobsByLoanNumber(paramMap);
		return list;
	}

	public LoanBorrowerCreditInfoDto getLoanBorrowerCreditInfoByLoanNumber(String loanNumber) {
		Map<String, Object> paramMap = new HashMap<String, Object>(1);
		paramMap.put("loanNumber", loanNumber);
		List<LoanBorrowerCreditInfoDto> list = loanDao.getLoanBorrowerCreditInfoByLoanNumber(paramMap);
		if (list == null || list.isEmpty())
			return null;
		return list.get(0);
	}

	public List<LoanBorrowerEntityDto> getLoanBorrowerEntityByLoanNumber(String loanNumber) {
		Map<String, Object> paramMap = new HashMap<String, Object>(1);
		paramMap.put("loanNumber", loanNumber);
		List<LoanBorrowerEntityDto> list = loanDao.getLoanBorrowerEntityByLoanNumber(paramMap);
		return list;
	}

	public LoanBorrowerLoanInfoDto getLoanBorrowerLoanInfoByLoanNumber(String loanNumber) {
		Map<String, Object> paramMap = new HashMap<String, Object>(1);
		paramMap.put("loanNumber", loanNumber);
		List<LoanBorrowerLoanInfoDto> list = loanDao.getLoanBorrowerLoanInfoByLoanNumber(paramMap);
		if (list == null || list.isEmpty())
			return null;
		return list.get(0);
	}

	public List<LoanBorrowerAssetDto> getLoanBorrowerAssetByLoanNumber(String loanNumber) {
		Map<String, Object> paramMap = new HashMap<String, Object>(1);
		paramMap.put("loanNumber", loanNumber);
		List<LoanBorrowerAssetDto> list = loanDao.getLoanBorrowerAssetByLoanNumber(paramMap);
		return list;
	}
	/**
	 * 
	 * @author lizhiqiang
	 * @throws Exception 
	 * @date 2016-12-28 下午6:13:42
	 * @see com.jy.modules.cims.component.loan.ICLoan#doReceiveLoanRedemption(java.util.List)
	 */
	@Override
	public String doReceiveLoanRedemption(List<RequestLoanRedemptionApplyLoanDTO> loanList) throws Exception {
		BigDecimal sumCreditorValue = BigDecimal.ZERO;

		// 生成流水号
		String dealCode = this.doGetDealCode();
				
		// 插入债权交易明细
		Map<String, Object> paramMap = new HashMap<String, Object>();
		TCMmCreditDealDetailDTO creditDealDetailDTO = null;
		TCMmCreditDetailDTO creditDetail = null;
		Map<String, Object> updateMap = new HashMap<String, Object>();
		for (RequestLoanRedemptionApplyLoanDTO loanDTO : loanList) {
			paramMap.clear();
			paramMap.put("dto", loanDTO);
			List<TCMmCreditDetailDTO> creditDetailList = dealDao.getCreditDetailListByLoan(paramMap);			
			creditDetail = creditDetailList.get(0);

			// 债权交易明细DTO组装
			creditDealDetailDTO = new TCMmCreditDealDetailDTO();
			creditDealDetailDTO.setDealStreamCode(dealCode);// 交易流水号
			creditDealDetailDTO.setAgreementCode(creditDetail.getAgreementCode());// 协议编号
			creditDealDetailDTO.setTransferId(loanDTO.getLoanNumber());// 债权转让编号
			creditDealDetailDTO.setCreditorId(loanDTO.getLoanNumber());// 债权编号
			creditDealDetailDTO.setCooperorgCode(creditDetail.getCooperorgCode());// 转让合作机构编号
			creditDealDetailDTO.setCreditorStatus(CimsConstant.CREDIT_STATUS_WIN);// 债权状态
			creditDealDetailDTO.setDeliverDate(loanDTO.getRedeemDate());// 交割日期
			creditDealDetailDTO.setRedeemDate(loanDTO.getRedeemDate());// 回购日期
			creditDealDetailDTO.setMakeCreditorValue(loanDTO.getMakeCreditorValue());// 本次转让债权价值
			creditDealDetailDTO.setCoreCreditStatus(creditDetail.getCoreCreditStatus());//
			creditDealDetailDTO.setThisRepaySum(creditDetail.getThisRepaySum());//
			creditDealDetailDTO.setThisCreditorValue(creditDetail.getThisCreditorValue());//
			creditDealDetailDTO.setCreateTime(new Timestamp(System.currentTimeMillis()));// 创建时间
			creditDealDetailDTO.setModifyTime(new Timestamp(System.currentTimeMillis()));//
			creditDealDetailDTO.setCostState(CimsConstant.COST_STATUS_WJ);
			// 保存关系表
			creditDealDetailService.insertTCMmCreditDealDetail(creditDealDetailDTO);
			
			// 更新债权明细表
			updateMap.clear();
			updateMap.put("id", creditDetail.getId());
			updateMap.put("chooseStatus", CimsConstant.CREDIT_REDEMPTION_UNCK);// 02-已经选择
			updateMap.put("redeemDate", loanDTO.getRedeemDate());
			buyBackDao.updateCreditChooseStatus(updateMap);

			// 汇总回购价格
			sumCreditorValue = sumCreditorValue.add(creditDealDetailDTO.getMakeCreditorValue());
		}

		// 交易流水DTO组装
		TCMmCooperorgDealDTO cooperorgDealDTO = new TCMmCooperorgDealDTO();
		cooperorgDealDTO.setDealCode(dealCode);// 交易流水号
		cooperorgDealDTO.setCooperorgCode(creditDetail.getCooperorgCode());// 合作机构
		cooperorgDealDTO.setDealDate(new Date());// 交易日期
		cooperorgDealDTO.setDealType(CimsConstant.DEAL_TYPE_LOAN_CREDIT_REDEEM);// 交易类型
		cooperorgDealDTO.setAgreementCode(creditDetail.getAgreementCode());// 协议编号
		cooperorgDealDTO.setContractCode(creditDetail.getContractCode());// 合约编号
		cooperorgDealDTO.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_CREATE);// 合作机构交易状态
		cooperorgDealDTO.setDetialNumber(loanList.size());// 明细数目
		cooperorgDealDTO.setSumCreditorValue(sumCreditorValue);// 汇总债权价值
		cooperorgDealDTO.setCreateTime(new Timestamp(System.currentTimeMillis()));// 创建时间
		cooperorgDealDTO.setRedemptionDate(loanList.get(0).getRedeemDate());// 回购日期
		cooperorgDealDTO.setModifyTime(new Timestamp(System.currentTimeMillis()));// 修改时间
		cooperorgDealService.insertTCMmCooperorgDeal(cooperorgDealDTO);

		return dealCode;
	}
	
}
